package mn.slide.laborberlin.main;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import mn.slide.laborberlin.db.DataLayer;
import mn.slide.laborberlin.db.DatabaseManager;
import mn.slide.laborberlin.model.Kapitel;
import mn.slide.laborberlin.tabgroup.GroupStarter;
import android.app.Activity;
import android.content.Intent;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.text.Html;
import android.text.SpannableStringBuilder;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class StartActivity extends Activity implements ReadDataFinish
{
	private Button			start;
	private TextView		text;
	ImageView				startImage;
	List<Kapitel>			kapitelList;
	public static String	PATH			= "/data/data/mn.slide.laborberlin.main/databases/";
	public static String	DATABASE_PATH	= PATH + "Labor.sqlite";
	public String			dateUrl			= "http://support.slide.mn/labor/test/relase_date.xml";

	@Override
	public void onCreate( Bundle savedInstanceState )
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.start);
		createDatabase();
		new DataLayer(this);
		GroupStarter.init();
		DatabaseManager.init(this);
		kapitelList = new ArrayList<Kapitel>();
		kapitelList = DatabaseManager.getInstance().getAllKapitel();
		Log.e("kapitelList", kapitelList.size() + "");
		DataLayer.layer.setKapitelList(kapitelList);
		DataLayer.layer.readDatabase(this);
		text = (TextView) findViewById(R.id.text);
		text.setText(getHtmlText());
		startImage = (ImageView) findViewById(R.id.start_image);
		Animation anim = AnimationUtils.loadAnimation(this, R.anim.grow_from_bottomleft_to_topright);
		startImage.setAnimation(anim);
		if (kapitelList.size() == 0)
		{
			finishReadData();
		}
		checkTime();
		start = (Button) findViewById(R.id.start);
		start.setOnClickListener(new OnClickListener()
		{
			public void onClick( View v )
			{
				finish();
				Intent intent = new Intent(StartActivity.this, TabBarActivity.class);
				startActivity(intent);
				overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
			}
		});
	}

	private SpannableStringBuilder getHtmlText()
	{
		SpannableStringBuilder htmlBuilder = new SpannableStringBuilder();

		htmlBuilder.append(Html.fromHtml("<b><font color=#998a77> " + getString(R.string.begin_str1) + "s</font><b><br><br>"));
		htmlBuilder.append(Html.fromHtml(getString(R.string.begin_str2).replaceAll("::", "<br><br>")));
		htmlBuilder.append(Html.fromHtml(getString(R.string.begin_str3)));

		return htmlBuilder;
	}

	@Override
	public void finishReadData()
	{
		// TODO Auto-generated method stub
		startImage.setVisibility(View.GONE);
	}

	public void createDatabase()
	{
		Log.d("createDatabase", "createDatabase");
		File path = new File(PATH);
		if (!path.exists())
			path.mkdirs();
		File file = new File(DATABASE_PATH);
		if (!file.exists())
		{
			AssetManager assetManager = getAssets();
			try
			{
				byte buf[] = new byte[1024 * 1024];
				OutputStream outputStream = new FileOutputStream(DATABASE_PATH);
				for (int i = 0; i < 3; i++)
				{
					InputStream inputStream = assetManager.open("Labor.sqlite" + i);
					inputStream.read(buf);
					outputStream.write(buf);
					inputStream.close();
				}
				outputStream.flush();
				outputStream.close();
				Log.d("YES", "YES");
			}
			catch (IOException e)
			{
				Log.d("tag", e.getMessage());
			}
		}
	}

	public void checkTime()
	{
		HttpGet get = new HttpGet(dateUrl);
		HttpClient httpClient = new DefaultHttpClient();
		HttpConnectionParams.setSoTimeout(httpClient.getParams(), 500);
		HttpResponse response;
		Calendar c = Calendar.getInstance();
		SimpleDateFormat df = new SimpleDateFormat("yyyy:MM:dd hh:mm");
		String nowTime = df.format(c.getTime());
		String array[] = nowTime.split(":");
		String array1[] = array[2].split(" ");

		try
		{
			response = httpClient.execute(get);
			HttpEntity entity = response.getEntity();
			XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
			factory.setNamespaceAware(true);
			XmlPullParser xpp = factory.newPullParser();
			xpp.setInput(entity.getContent(), "UTF-8");
			int eventType;
			eventType = xpp.getEventType();
			while (eventType != XmlPullParser.END_DOCUMENT)
			{

				if (eventType == XmlPullParser.START_TAG)
				{
					if (xpp.getName().equals("Date"))
					{
						String value = xpp.getAttributeValue(null, "value");
						Log.d("valiue", value);
						String date[] = value.split(":");
						String date1[] = date[2].split(" ");
						if (Integer.parseInt(date[0]) <= Integer.parseInt(array[0]) && Integer.parseInt(date[1]) <= Integer.parseInt(array[1]) && Integer.parseInt(date1[0]) <= Integer.parseInt(array1[0]) && Integer.parseInt(date1[1]) <= Integer.parseInt(array1[1]) && Integer.parseInt(date[3]) <= Integer.parseInt(array[3]))
						{
							TabBarActivity.drawable = R.drawable.tab_update;
						}
					}
				}
				eventType = xpp.next();
			}
		}
		catch (ClientProtocolException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (XmlPullParserException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}
